package com.liuhung.base.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;

import com.liuhung.base.util.HtmlUtil;
import com.liuhung.ash.security.entity.Model;
import com.liuhung.ash.security.entity.Users;
import com.liuhung.ash.security.service.ModelService;
import com.liuhung.ash.security.service.UsersService;

import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

public class BaseAction {

	public final static String SUCCESS = "success";

	public final static String MSG = "msg";

	public final static String DATA = "data";

	public final static String LOGOUT_FLAG = "logoutFlag";

	/**
	 * 用户种类 0 管理员 1 医疗机构用户 2 商业用户
	 */
	public final static Integer USER_TYPE_MASTER = 0;
	public final static Integer USER_TYPE_INSTITUTIONS = 1;
	public final static Integer USER_TYPE_TENANT = 2;

	public static Users loginUser;
	public static List<Model> models;

	@Autowired(required = false)
	ModelService modelService;

	@Autowired(required = false)
	UsersService usersService;
	
	/**
	 * 日期转换
	 * @param binder
	 * @throws ServletException
	 */
	@InitBinder
    protected void initBinder(
            WebDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class,
                new ByteArrayMultipartFileEditor());
         
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                dateFormat.setLenient(false);
                binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	/**
	 * 获取浏览器信息
	 * 
	 * @param request
	 * @return
	 */
	public String getUserBrowser(HttpServletRequest request) {
		UserAgent useragent = new UserAgent(request.getHeader("user-agent"));
		return useragent.getBrowser() + " " + useragent.getBrowserVersion();
	}

	/**
	 * 获取操作系统信息
	 * 
	 * @param request
	 * @return
	 */
	public OperatingSystem getOs(HttpServletRequest request) {
		UserAgent useragent = new UserAgent(request.getHeader("user-agent"));
		return useragent.getOperatingSystem();

	}
	
	/**
	 * 获取当前用户可操作的model
	 * 
	 * @param request
	 * @return
	 */
	public List<Model> getModels(HttpServletRequest request) {
		Users users = getLocalUser(request);
		System.out.println("为"+users.getUsername()+"查找模块");
		List<Model> models = modelService.queryByUsers(users.getId());
		System.out.println("模块数:"+models.size());
		List<Model> models2 = modelService.queryRoot();
		List<Model> models3 = new ArrayList<Model>();
		for (Model m : models2) {
			List<Model> childmodels = new ArrayList<Model>();
			for (Model cm : m.getChildren()) {
				if (hasModel(cm, models)) {
					childmodels.add(cm);
				}
			}
			m.setChildren(childmodels);
			if (m.getChildren().size() > 0) {
				models3.add(m);
			}
			 System.out.println("模块:"+m.getName()+"子模块数:"+m.getChildren().size());
		}
		request.getSession().setAttribute("LOGIN_USERS_MODELS", models3);
		return models3;
	}

	/**
	 * 获取当前的系统根url
	 */
	public String getWebRoot(HttpServletRequest request) {
		String webRoot = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + "/";
		return webRoot;
	}

	/**
	 * 获取当前的系统根path
	 */
	public String getBasePath(HttpServletRequest request) {
		return request.getRealPath("/");
	}

	/**
	 * 获取当前用户
	 * 
	 * @param request
	 * @return
	 */
	public static Users getLocalUser(HttpServletRequest request) {
		Users users = new Users();
		users = (Users) request.getSession().getAttribute("LOGIN_USERS");
		return users;
	}

	/**
	 * 设置当前用户
	 * 
	 * @param request
	 * @return
	 */
	public void setLocalUser(Users users, HttpServletRequest request) {
		request.getSession().setAttribute("LOGIN_USERS", users);
		loginUser = users;
	}
	/**
	 * 检查列表中是否包含有此model
	 * 
	 * @param model
	 * @param models
	 * @return
	 */
	public boolean hasModel(Model model, List<Model> models) {
		boolean hasModel = false;
		for (Model m : models) {
			if (m.getId()==model.getId()) {
				hasModel = true;
				break;
			}
		}
		return hasModel;
	}

	/**
	 * 登出当前用户
	 * 
	 * @param request
	 * @return
	 */
	public void setLocalUserNull(HttpServletRequest request) {
		request.getSession().setAttribute("LOGIN_USERS", null);
	}

	/**
	 * 所有ActionMap 统一从这里获取
	 * 
	 * @return
	 */
	public Map<String, Object> getRootMap() {
		Map<String, Object> rootMap = new HashMap<String, Object>();
		return rootMap;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ModelAndView forword(String viewName, Map context) {
		return new ModelAndView(viewName, context);
	}

	public ModelAndView error(String errMsg) {
		return new ModelAndView("error");
	}

	/**
	 * 
	 * 提示成功信息 同时返回数据
	 * 
	 * @param message
	 * 
	 */
	public void sendSuccessMessage(HttpServletResponse response, String message, Object data) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, true);
		result.put("status", 1);
		result.put(MSG, message);
		result.put(DATA, data);
		result.put("errorCode", 200);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 
	 * 提示成功信息
	 * 
	 * @param message
	 * 
	 */
	public void sendSuccessMessage(HttpServletResponse response, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, true);
		result.put(MSG, message);
		result.put("status", 1);
		result.put("errorCode", 200);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 
	 * 提示失败信息
	 * 
	 * @param message
	 * 
	 */
	public void sendFailureMessage(HttpServletResponse response, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, false);
		result.put("status", 0);
		result.put(MSG, message);
		result.put("errorCode", 500);// 常规未归类错误
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 
	 * 提示失败信息
	 * 
	 * @param message
	 * 
	 */
	public void sendFailureMessage(HttpServletResponse response, int errorCode, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, false);
		result.put("status", 0);
		result.put("errorCode", errorCode);
		result.put(MSG, message);
		HtmlUtil.writerJson(response, result);
	}
	/**
	 * ***************************************
	 * @Description
	 * @param request
	 * @param key
	 * @return   
	 * @author liuhung
	 ***************************************
	 */
	public String getStringParameter(HttpServletRequest request, String key) {
		String r = null;
		String s = request.getParameter(key) == null ? null : request.getParameter(key);
		return r;
	}
	/*****************************************
	 * @Description 获取前台传递来的Integer参数
	 * @param request
	 * @param key
	 * @return   
	 * @author liuhung
	 ***************************************
	 */
	
	public Integer getIntegerParameter(HttpServletRequest request, String key) {
		Integer r = null;
		String s = request.getParameter(key) == null ? null : request.getParameter(key);
		if (s == null || StringUtil.isBlank(s))
			r = null;
		else if (!isInteger(s))
			r = null;
		else
			r = Integer.parseInt(s);
		return r;
	}
	/*****************************************
	 * @Description 获取前台传递来的Float参数
	 * @param request
	 * @param key
	 * @return   
	 * @author liuhung
	 ***************************************
	 */
	public Float getFloatParameter(HttpServletRequest request, String key) {
		Float r = null;
		String s = request.getParameter(key) == null ? null : request.getParameter(key);
		if (s == null || StringUtil.isBlank(s))
			r = null;
		else if (!isFloat(s))
			r = null;
		else
			r = Float.valueOf(s);
		return r;
	}
	/*****************************************
	 * @Description 获取前台传递来的Float参数
	 * @param request
	 * @param key
	 * @return   
	 * @author liuhung
	 ***************************************
	 */
	public Double getParameter(HttpServletRequest request, String key) {
		Double r = null;
		String s = request.getParameter(key) == null ? null : request.getParameter(key);
		if (s == null || StringUtil.isBlank(s))
			r = null;
		else if (!isDouble(s))
			r = null;
		else
			r = Double.parseDouble(s);
		return r;
	}
	/*****************************************
	 * @Description 判断是否为数字;
	 * @param value
	 * @return   
	 * @author liuhung
	 ***************************************
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	/**
	  * 判断字符串是否是浮点数
	  */
	 public static boolean isDouble(String value) {
	  try {
	   Double.parseDouble(value);
	   if (value.contains("."))
		   return true;
	   return false;
	  } catch (NumberFormatException e) {
	   return false;
	  }
	 }
	 /**
	  * 判断字符串是否是浮点数
	  */
	 public static boolean isFloat(String value) {
	  try {
	   Float.parseFloat(value);
	   if (value.contains("."))
		   return true;
	   return false;
	  } catch (NumberFormatException e) {
	   return false;
	  }
	 }

	 /**
	  * 判断字符串是否是数字
	  */
	 public static boolean isNumber(String value) {
	  return isInteger(value) || isDouble(value);
	 }

}
